<template>
  <el-form
      ref="clientFormRef"
      :model="clientForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
  >
    <el-form-item label="客户名称" prop="name">
      <el-input v-model="clientForm.name" placeholder="客户名称" />
    </el-form-item>
    <el-form-item label="客户地址" prop="address">
      <el-input v-model="clientForm.address" placeholder="客户地址" />
    </el-form-item>
    <el-form-item label="联系方式" prop="phone">
      <el-input v-model="clientForm.phone" placeholder="联系方式" />
    </el-form-item>
    <el-form-item label="水票数量" prop="custTicket">
      <el-input v-model="clientForm.custTicket" placeholder="水票数量" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">
        提交
      </el-button>
      <el-button @click="query">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {ref,reactive,onMounted} from "vue";
import request from "@/api/request";
import {ElMessage} from "element-plus";
import router from "@/router";

const clientFormRef = ref(null);
const clientForm = reactive({
  id:null,
  name:'',
  address:'',
  phone:'',
  custTicket:''
})
const rules = reactive({
  name: [
    {required: true, message: '请输入客户名称', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入客户地址', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入联系方式', trigger: 'blur'}
  ],
  custTicket: [
    {required: true, message: '请输入水票数量', trigger: 'blur'}
  ]
})
const submitForm = () => {
  if(clientForm.id===null) {
    clientFormRef.value.validate((valid) => {
      if (valid) {
        request.post('/clients/addclient', clientForm).then(resp => {
          if (resp.code === 20000) {
            ElMessage.success(resp.data);
            router.replace('/client');
          } else {
            ElMessage.error(resp.data);
          }
        })
      }
    })
  }else{
    clientFormRef.value.validate((valid) => {
      if (valid) {
        request.put('/clients/updclient', clientForm).then(resp => {
          if (resp.code === 20000) {
            ElMessage.success(resp.data);
            router.replace('/client');
          } else {
            ElMessage.error(resp.data);
          }
        })
      }
    })
  }
}
const query = () => {
  router.replace('/client');
}

onMounted(()=>{
  if(localStorage.getItem("clientId")!=0) {
    request.get('/clients/getclientbyid/' + localStorage.getItem("clientId")).then(resp => {
      if(resp){
        clientForm.id = resp.data.id;
        clientForm.name = resp.data.name;
        clientForm.address = resp.data.address;
        clientForm.phone = resp.data.phone;
        clientForm.custTicket = resp.data.custTicket;
      }
    })
  }
})
</script>